﻿using JinfuyuanProject.Entity;
using JinfuyuanProject.Repository.Interface;
using JinfuyuanProject.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNet.Utilities;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using JinfuyuanProject.Entity.ViewModels;
using System.Collections;
using DocumentFormat.OpenXml.Office2010.ExcelAc;

namespace JinfuyuanProject.Service
{
    /*
*  
* 母子涵
* 2025-04-23
*/
    public class ParturientService : IParturientService
    {
        private readonly IParturientRepository _ParturientRepository;
        private JinfuyuanDbContext _db;
        public ParturientService(IParturientRepository ParturientRepository, JinfuyuanDbContext db)
        {
            _ParturientRepository = ParturientRepository;
            _db = db;
        }
        #region 基本方法
        public bool Delete(Parturient Parturient)
        {
            return _ParturientRepository.Delete(Parturient);
        }

        public IQueryable<Parturient> GetList()
        {
            return _ParturientRepository.GetList();
        }

        public Parturient GetModel(int Id)
        {
            return _ParturientRepository.GetModel(Id);
        }

        public int Insert(Parturient Parturient)
        {
            return _ParturientRepository.Insert(Parturient);
        }

        public bool Update(Parturient Parturient)
        {
            return _ParturientRepository.Update(Parturient);
        }
        #endregion
        #region 业务写法
        //事务
        //insert产妇  insert宝宝  insert 合同
        public ResMessage CreateMother(Parturient parturient, List<Baby> babies,Contract contract, string SalesmanNumbers)
        {
            
            if (string.IsNullOrEmpty(SalesmanNumbers))
            {
                parturient.Salesman = 0;
            }
            else
            {
                var salesmanId = _db.Staff
                        .Where(x => x.Numbers == SalesmanNumbers)
                        .Select(x => x.Id)
                        .FirstOrDefault();
                parturient.Salesman= salesmanId;
                contract.EmpId = salesmanId;
            }
            var trans = _db.Database.BeginTransaction(); // 开始事务
            try
            {
                _db.Parturient.Add(parturient);
                _db.SaveChanges();
                contract.ParturientId = parturient.Id;
               
                _db.Contract.Add(contract);
                foreach (var baby in babies)
                    {
                        baby.ParturientId = parturient.Id; 
                        baby.IsDelete = 0;
                        baby.CreateTime = DateTime.Now;
                        _db.Baby.Add(baby);  
                    }
                 
                trans.Commit();
                _db.SaveChanges();
                return ResMessage.Success("");
            }
            catch (Exception ex)
            {
                //日志 记录异常信息
                trans.Rollback();
                return ResMessage.Fail(ex.Message);
            }
        }
        //合同文档生成
        public ResMessage GenerateDocument(Parturient parturient, List<Baby> babies, string PackagePrice, string templatePath, string outputPath)
        {    //获得表格数据
            var packageServices = _db.PackageServices.Where(x=>x.ComboId== parturient.PackageId)
             .Join(_db.Services,
           p => p.ServiceId, 
           c => c.Id,       
           (p, c) => new PackageSerVM
           {
            ServiceName=c.ServiceName,
               ServiceNumber = p.ServiceNumber,
               ServicePrice = c.ServicePrice,
               ServiceType=c.ServiceType,

           }).ToList();
            // 复制模板文件
            File.Copy(templatePath, outputPath, true);
            // 处理文档替换
            using (WordprocessingDocument doc = WordprocessingDocument.Open(outputPath, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;
                ProcessDocumentContent(mainPart, parturient,PackagePrice, babies);
                ProcessServiceTable(mainPart, packageServices);
                mainPart.Document.Save();
            }
            return ResMessage.Success("");
        }
        // 核心替换逻辑
        private void ProcessDocumentContent(MainDocumentPart mainPart, Parturient parturient, string PackagePrice, List<Baby> babies)
        {
            var replacements = new Dictionary<string, string>
            {
                ["{{ParturientName}}"] = parturient.ParturientName,
                ["{{ParturientPhone}}"] = parturient.ParturientPhone,
                ["{{CardId}}"] = parturient.CardId,
                ["{{EmergencyContacts}}"] = parturient.EmergencyContacts,
                ["{{EmergencyContactsPhone}}"] = parturient.EmergencyContactsPhone,
                ["{{Address}}"] = parturient.Address,
                ["{{BabyName}}"] = string.Join(", ", babies.Select(b => b.BabyName)),
                ["{{PackagePrice}}"] = NumberToChineseConverter.ConvertToChineseAmount(decimal.Parse(PackagePrice)),
            };
            foreach (var text in mainPart.Document.Descendants <DocumentFormat.OpenXml.Wordprocessing.Text>())
            {
                foreach (var key in replacements.Keys)
                {
                    if (text.Text.Contains(key))
                    {
                        text.Text = text.Text.Replace(key, replacements[key]);
                    }
                }
            }
        }
        private void ProcessServiceTable(MainDocumentPart mainPart, List<PackageSerVM> services)
        {
            // 定位目标表格（假设第一个表格为服务列表）
            var table = mainPart.Document.Body.Descendants<Table>().FirstOrDefault();
            if (table == null) return;
            // 获取模板行（假设首行为标题行，第二行为数据模板）
            var rows = table.Elements<TableRow>().ToList();
            if (rows.Count < 2) return;
            var templateRow = rows[1];
            var parent = table.Parent;
            // 清空原有数据行（保留标题行）
            for (int i = rows.Count - 1; i >= 1; i--)
            {
                rows[i].Remove();
            }
            // 动态填充数据
            foreach (var service in services)
            {
                var newRow = (TableRow)templateRow.CloneNode(true);
                // 结构化填充单元格
                var cells = newRow.Elements<TableCell>().Take(4).ToList();
                if (cells.Count >= 4)
                {
                    SetCellText(cells[0], service.ServiceName);
                    SetCellText(cells[1], service.ServiceNumber.ToString());
                    SetCellText(cells[2], service.ServicePrice.ToString());
                    SetCellText(cells[3], GetServiceTypeName(service.ServiceType));
                }
                table.AppendChild(newRow);
            }
            // 移除模板行
            templateRow.Remove();
        }
        // 安全设置单元格内容
        private void SetCellText(TableCell cell, string value)
        {
            // 先尝试清理空段落
            var emptyParagraphs = cell.Elements<Paragraph>()
                                    .Where(p => !p.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().Any())
                                    .ToList();

            foreach (var para in emptyParagraphs)
            {
                para.Remove();
            }
            // 获取或创建有效段落
            var paragraph = cell.Elements<Paragraph>().FirstOrDefault();
            if (paragraph == null)
            {
                paragraph = new Paragraph();
                cell.Append(paragraph);
            }
            // 获取或创建文本运行
            var run = paragraph.Elements<Run>().FirstOrDefault();
            if (run == null)
            {
                run = new Run();
                paragraph.Append(run);
            }
            // 设置文本内容
            var text = run.Elements<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault();
            if (text != null)
            {
                text.Text = value;
            }
            else
            {
                run.Append(new DocumentFormat.OpenXml.Wordprocessing.Text(value));
            }
        }
        private string GetServiceTypeName(int? typeCode)
        {
            switch (typeCode)
            {
                case 1:
                    return "宝宝服务";
                case 2:
                    return "美容服务";
                case 3:
                    return "护理服务";
                default:
                    return "其他服务";
            }
        }
        //数字转中文
        public class NumberToChineseConverter
        {
            private static readonly string[] ChineseNumbers =
                { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
            private static readonly string[] ChineseUnits =
                { "", "拾", "佰", "仟", "万", "亿" };

            public static string ConvertToChineseAmount(decimal number)
            {
                if (number == 0)
                    return "零元";
                string strNumber = number.ToString("F2");  // 保留两位小数
                string integerPart = strNumber.Split('.')[0];
                string decimalPart = strNumber.Split('.')[1];

                string result = ConvertIntegerPartToChinese(integerPart);
                if (decimalPart != "00")
                {
                    result += "点";
                    result += decimalPart[0] != '0' ? ChineseNumbers[int.Parse(decimalPart[0].ToString())] : "";
                    result += decimalPart[1] != '0' ? ChineseNumbers[int.Parse(decimalPart[1].ToString())] : "";
                }
                result += "元";
                return result;
            }
            private static string ConvertIntegerPartToChinese(string integerPart)
            {
                string result = "";
                int length = integerPart.Length;
                bool hasZero = false;
                for (int i = 0; i < length; i++)
                {
                    int digit = int.Parse(integerPart[i].ToString());
                    if (digit != 0)
                    {
                        if (hasZero)
                        {
                            result += ChineseNumbers[0];
                            hasZero = false;
                        }
                        result += ChineseNumbers[digit] + ChineseUnits[length - i - 1];
                    }
                    else
                    {
                        hasZero = true;
                    }
                }
                return result;
            }
        }
        //房间入住时输入孕妇名自动填充
        public Hashtable GetPmessger(string keywords)
        {
            Hashtable hashtable = new Hashtable();
            //关联孕妇表和合同表
            List<ParturientContractVM> parturientContractVMs = _db.Parturient.Where(x=>x.HomeId==0)
                .Join(_db.Contract, p => p.Id, c => c.ParturientId, (p, c) => new ParturientContractVM
            {
                Id = p.Id,
                ParturientName = p.ParturientName,
                ContractNumber=c.ContractNumber,
                PackageId=c.PackageId,
                Cid=c.Id,
            }).Where(x => x.ParturientName.Contains(keywords)).ToList();
      
            hashtable["code"] = 0;
            hashtable["msg"] = "success";
            hashtable["data"] = parturientContractVMs;
            hashtable["count"] = parturientContractVMs.Count();
            return hashtable;
        }

        #endregion
    }
}

